package club.jdiy.admin.ueditor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import club.jdiy.admin.ueditor.define.ActionMap;
import club.jdiy.admin.ueditor.define.AppInfo;
import club.jdiy.admin.ueditor.define.BaseState;
import club.jdiy.admin.ueditor.define.State;
import club.jdiy.admin.ueditor.hunter.FileManager;
import club.jdiy.admin.ueditor.hunter.ImageHunter;
import club.jdiy.admin.ueditor.upload.Base64Uploader;
import club.jdiy.admin.ueditor.upload.BinaryUploader;
import club.jdiy.core.AppContext;

public class ActionEnter {
    private final HttpServletRequest request;
    private final String actionType;
    private final ConfigManager configManager;
    private final AppContext context;


    public ActionEnter(AppContext appContext, HttpServletRequest request, String rootPath) {
        this.context = appContext;
        this.request = request;
        this.actionType = request.getParameter("action");
        this.configManager = ConfigManager.getInstance(rootPath);
    }

    public String exec() {

        String callbackName = this.request.getParameter("callback");

        if (callbackName != null) {
            if (!validCallbackName(callbackName)) {
                return new BaseState(false, AppInfo.ILLEGAL).toJSONString();
            }
            return callbackName + "(" + this.invoke() + ");";
        } else {
            return this.invoke();
        }

    }

    public String invoke() {

        if (actionType == null || !ActionMap.mapping.containsKey(actionType)) {
            return new BaseState(false, AppInfo.INVALID_ACTION).toJSONString();
        }

        if (this.configManager == null || !this.configManager.valid()) {
            return new BaseState(false, AppInfo.CONFIG_ERROR).toJSONString();
        }

        State state = null;

        int actionCode = ActionMap.getType(this.actionType);

        Map<String, Object> conf;

        switch (actionCode) {

            case ActionMap.CONFIG:
                return this.configManager.getAllConfig().toString();

            case ActionMap.UPLOAD_IMAGE:
            case ActionMap.UPLOAD_SCRAWL:
            case ActionMap.UPLOAD_VIDEO:
            case ActionMap.UPLOAD_FILE:
                conf = this.configManager.getConfig(actionCode);
                state = doUpload(conf);
                break;

            case ActionMap.CATCH_IMAGE:
                conf = configManager.getConfig(actionCode);
                String[] list = this.request.getParameterValues((String) conf.get("fieldName"));
                state = new ImageHunter(conf).capture(list);
                break;

            case ActionMap.LIST_IMAGE:
            case ActionMap.LIST_FILE:
                conf = configManager.getConfig(actionCode);
                int start = this.getStartIndex();
                state = new FileManager(conf).listFile(start);
                break;

        }

        return state == null ? null : state.toJSONString();

    }

    private State doUpload(Map<String, Object> conf) {
        String filedName = (String) conf.get("fieldName");
        return "true".equals(conf.get("isBase64"))
                ? Base64Uploader.save(context, this.request.getParameter(filedName), conf)
                : BinaryUploader.save(context, request, conf);
    }

    public int getStartIndex() {

        String start = this.request.getParameter("start");

        try {
            return Integer.parseInt(start);
        } catch (Exception e) {
            return 0;
        }

    }

    /**
     * callback参数验证
     */
    private boolean validCallbackName(String name) {
        return name.matches("^[a-zA-Z_]+[\\w0-9_]*$");

    }

}